import {Alert, Checkbox, Icon, Input} from 'antd';
import {FormattedMessage, formatMessage} from 'umi-plugin-react/locale';
import React, {Component} from 'react';

import {CheckboxChangeEvent} from 'antd/es/checkbox';
import {Dispatch} from 'redux';
import {FormComponentProps} from 'antd/es/form';
import Link from 'umi/link';
import {connect} from 'dva';
import {max} from 'moment';
import {StateType} from './model';
import LoginComponents from './components/Login';
import styles from './style.less';

const {Tab, UserName, Password, VerifyCode, Mobile, Captcha, Submit} = LoginComponents;

interface LoginProps {
  dispatch: Dispatch<any>;
  userLogin: StateType;
  submitting: boolean;
}

interface LoginState {
  type: string;
  autoLogin: boolean;
}

export interface FormDataType {
  userName: string;
  password: string;
  mobile: string;
  captcha: string;
}

@connect(
  ({
     userLogin,
     loading,
   }: {
    userLogin: StateType;
    loading: {
      effects: {
        [key: string]: string;
      };
    };
  }) => ({
    userLogin,
    submitting: loading.effects['userLogin/login'],
  }),
)
class Login extends Component<LoginProps, LoginState> {
  loginForm: FormComponentProps['form'] | undefined | null = undefined;

  state: LoginState = {
    type: 'account',
    autoLogin: true,
  };

  changeAutoLogin = (e: CheckboxChangeEvent) => {
    this.setState({
      autoLogin: e.target.checked,
    });
  };

  handleSubmit = (err: any, values: FormDataType) => {
    const {type} = this.state;
    let _this = this
    if (!err) {
      const {dispatch} = this.props;
      dispatch({
        type: 'userLogin/login',
        payload: {
          ...values,
          type,
          onSuccess: () => {
            dispatch({
              type: 'global/fetchUserInfo',
              payload: {},
            });
          },
        },
        callback(res: any) {
          if (res) {
            _this.setState({
              needVerifyCode: res.content.needVerifyCode
            })
          }
        }
      });
    }
  };

  onTabChange = (type: string) => {
    this.setState({type});
  };

  onGetCaptcha = () =>
    new Promise((resolve, reject) => {
      if (!this.loginForm) {
        return;
      }
      this.loginForm.validateFields(['mobile'], {}, (err: any, values: FormDataType) => {
        if (err) {
          reject(err);
        } else {
          const {dispatch} = this.props;
          ((dispatch({
            type: 'userLogin/getCaptcha',
            payload: values.mobile,
          }) as unknown) as Promise<any>)
            .then(resolve)
            .catch(reject);
        }
      });
    });

  renderMessage = (content: string) => (
    <Alert style={{marginBottom: 24}} message={content} type="error" showIcon/>
  );

  render() {
    const {userLogin, submitting} = this.props;
    const {status, type: loginType} = userLogin;
    const {type, autoLogin} = this.state;
    return (
      <div className={styles.main}>
        <LoginComponents
          defaultActiveKey={type}
          onTabChange={this.onTabChange}
          onSubmit={this.handleSubmit}
          ref={(form: any) => {
            this.loginForm = form;
          }}
        >
          {/* <Tab key="account" tab={formatMessage({ id: 'user-login.login.tab-login-credentials' })}> */}
          <style>{`
          .ant-tabs-nav-scroll {
            opacity: 0;
            height: 0;
          }
          .ant-input-group-addon{
            padding: initial;
          }
          img {
            vertical-align: middle;
            // border-style: none;
            height: 36px;
            border-bottom-right-radius: 0px;
            border-top-right-radius: 0px;
            border-top-left-radius: 0;
            border-bottom-left-radius: 0;
            // border: 1px solid #d9d9d9;
            // margin-right: 0px;
            margin-top: 0px;
           }
          `}</style>
          <Tab key="account" type="editable-card">
            {status === 'error' &&
            loginType === 'account' &&
            !submitting &&
            this.renderMessage(
              formatMessage({id: 'user-login.login.message-invalid-credentials'}),
            )}
            <UserName
              name="loginId"
              placeholder={`${formatMessage({id: 'user-login.login.userName'})}`}
              onChange={()=>this.handleSubmit}
              rules={[
                {
                  required: true,
                  message: formatMessage({id: 'user-login.userName.required'}),
                },
              ]}
            />
            <Password
              name="password"
              placeholder={`${formatMessage({id: 'user-login.login.password'})}`}
              rules={[
                {
                  required: true,
                  message: formatMessage({id: 'user-login.password.required'}),
                },
              ]}
              onPressEnter={e => {
                e.preventDefault();
                this.loginForm.validateFields(this.handleSubmit);
              }}
            />
            {this.state.needVerifyCode ? <VerifyCode
              name="verifyCode"
              placeholder={`${formatMessage({id: 'user-login.login.verifyCode'})}`}
              rules={[
                {
                  required: true,
                  len: 4,
                  message: formatMessage({ id: 'user-login.verifyCode.required' }),
                },
              ]}
              onPressEnter={e => {
                e.preventDefault();
                this.loginForm.validateFields(this.handleSubmit);
              }}
            /> : null}
          </Tab>
          <Tab key="mobile" style={{display: 'none'}}>
            {status === 'error' &&
            loginType === 'mobile' &&
            !submitting &&
            this.renderMessage(
              formatMessage({id: 'user-login.login.message-invalid-verification-code'}),
            )}
            <Mobile
              name="mobile"
              placeholder={formatMessage({id: 'user-login.phone-number.placeholder'})}
              rules={[
                {
                  required: true,
                  message: formatMessage({id: 'user-login.phone-number.required'}),
                },
                {
                  pattern: /^1\d{10}$/,
                  message: formatMessage({id: 'user-login.phone-number.wrong-format'}),
                },
              ]}
            />
            <Captcha
              name="captcha"
              placeholder={formatMessage({id: 'user-login.verification-code.placeholder'})}
              countDown={120}
              onGetCaptcha={this.onGetCaptcha}
              getCaptchaButtonText={formatMessage({id: 'user-login.form.get-captcha'})}
              getCaptchaSecondText={formatMessage({id: 'user-login.captcha.second'})}
              rules={[
                {
                  required: true,
                  message: formatMessage({id: 'user-login.verification-code.required'}),
                },
              ]}
            />
          </Tab>
          <div>
            <Checkbox checked={autoLogin} onChange={this.changeAutoLogin}>
              <FormattedMessage id="user-login.login.remember-me"/>
            </Checkbox>
            <a style={{float: 'right'}} href="/user/forgotPsd">
              <FormattedMessage id="user-login.login.forgot-password"/>
            </a>
          </div>
          <Submit loading={submitting}>
            <FormattedMessage id="user-login.login.login"/>
          </Submit>
          <div className={styles.other}>
            {/*<FormattedMessage id=" user-login.login.sign-in-with" />*/}
            <Icon className={styles.icon} theme="outlined"/>
            <Link className={styles.register} to="/user/register">
              <FormattedMessage id="user-login.login.signup"/>
            </Link>
          </div>
        </LoginComponents>
      </div>
    );
  }
}

export default Login;
